import pygame, sys
from pygame.locals import *

pygame.init()

FPS = 10 # frames per second setting
fpsClock = pygame.time.Clock()

# set up the window
DISPLAYSURF = pygame.display.set_mode((800, 700), 0, 32)
pygame.display.set_caption('模拟自由落体运动')

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED   = (255, 0, 0)
GREEN = (0, 255, 0)
GRAY  = (200, 200, 0)

orgx = 120
orgy = 60

ball_1_x = orgx
ball_1_y = orgy

ball_2_x = orgx + 360
ball_2_y = orgy

time = 0

IsFall = False

''' 上一时间点 时 经过的总的高度 '''
lasth = 0

''' 重力常数 '''
gravity = 4

def FreeFall():
    global IsFall, time, ball_1_y, ball_1_x, ball_2_y, lasth, gravity
    if IsFall == True:
        if time < 18:
            
            h = 0.5 * gravity * (time * time) # h = (g*t*t)/2
            print(" t = %2d : h = %3d d = %3d "%(time, h, h-lasth))

            lasth = h
            
            ball_1_y = h + orgy
            ball_1_x += 20

            ball_2_y = h + orgy
            time += 1
        else:
            #initEvn()
            IsFall = False
            time = 0

def initEvn():
    global time, IsFall, ball_1_y, ball_1_x, ball_2_y, ball_2_x, lasth
    time = 0
    IsFall = True
    lasth = 0
    ball_1_y = orgy
    ball_2_y = orgy
    ball_1_x = orgx
    ball_2_x = orgx + 360
    drawBg()
    pygame.draw.circle(DISPLAYSURF, pygame.Color("RED"), (ball_1_x, ball_1_y), 8)
    pygame.draw.circle(DISPLAYSURF, pygame.Color("GREEN"), (ball_2_x, ball_2_y), 8)
    
def drawBg():
    ''' 填充背景 白色 '''
    DISPLAYSURF.fill(pygame.Color("WHITE"))

    for x in range(orgx, 621, 20):
        if not (x-orgx)%100:
            color = BLACK
        else:
            color = GRAY
        ''' 画竖线 '''
        pygame.draw.line(DISPLAYSURF, color, (x, orgy), (x, orgy+600))

    for y in range(orgy, 661, 20):
        if not (y-orgy)%100:
            color = BLACK
        else:
            color = GRAY
        ''' 画横线 '''
        pygame.draw.line(DISPLAYSURF, color, (orgx, y), (orgx+500, y))

''' 画背景网格和初始位置小球 '''
drawBg()

''' 主循环 '''
while True: # the main game loop
    #DISPLAYSURF.fill(WHITE)
    #pygame.draw.line(DISPLAYSURF, BLACK, (orgx, orgy), (orgx+500, orgy))
    
    #画背景网格，注释掉的话， 显示的是一连串的轨迹
    drawBg()
    
    pygame.draw.circle(DISPLAYSURF, pygame.Color("RED"), (ball_1_x, ball_1_y), 8)
    pygame.draw.circle(DISPLAYSURF, pygame.Color("GREEN"), (ball_2_x, ball_2_y), 8)
    
    for event in pygame.event.get():
        ''' 键盘事件 '''
        if (event.type == KEYDOWN):
            ''' 空格键按下 且 不在降落过程中 '''
            if event.key == K_SPACE and not IsFall:
                initEvn()
        elif event.type == QUIT:
            pygame.quit()
            sys.exit()

    ''' 执行自由落体函数 '''
    FreeFall()
    
    pygame.display.update()
    fpsClock.tick(FPS)
